package com.yzg.sign.project.service.impl;



import com.alibaba.fastjson.JSON;
import com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Util;
import com.yzg.sign.project.common.*;
import com.yzg.sign.project.domain.Upload;
import com.yzg.sign.project.repository.UploadRepository;
import com.yzg.sign.project.service.UploadService;
import com.yzg.sign.project.token.TokenUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.transaction.Transactional;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service
@Transactional
public class UploadServiceImpl implements UploadService
{

     @Autowired
     private UploadRepository uploadRepository;

    @Autowired
     private TokenUtils tokenUtils;

     @Value("${upload.windows.filePath}")
     private  String  path ;





    @Override
    public Result<String> delete(String id)
    {
        Upload upload = uploadRepository.getOne(Long.valueOf(id));
        if(upload!=null)
        {
            UploadUtil.deleteDir(path+upload.getPath());
            uploadRepository.delete(upload);
            return Result.<String>builder().success().build();
        }
        return Result.<String>builder().fail().message("对象不存在！").build();
    }

    @Override
    public Result<Upload> upload(MultipartFile file)
    {

        Upload upload = new Upload();
        upload.setOriginName(file.getOriginalFilename());
        try {
           JSONObject object = BaiDuUtils.getClient().asr(file.getBytes(),"wav",16000,null);
            System.out.println(object.toString());
            if(object.getInt("err_no")==0)
            {
                JSONArray array = object.getJSONArray("result");
                upload.setContent(array.getString(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        List<String> paths = UploadUtil.save(Arrays.asList(file));
        if(!paths.isEmpty())
        {
            upload.setPath(paths.get(0));
        }
        upload.setType("chat");
        upload.setRelativeId(tokenUtils.getLoginUser().getOpenId());
        Upload  res = uploadRepository.saveAndFlush(upload);
        List<Upload> count = uploadRepository.findByRelativeId(tokenUtils.getLoginUser().getOpenId());
        if(count.size()<=5)
        {
            TianCongUtils.addSample(tokenUtils.getUserInfo().getOpenId(), String.valueOf(count.size()),upload.getContent(),new File(path.replace("\\uploadFile","")+upload.getPath()));
            if(count.size()==5)
            {
                TianCongUtils.trainmodel(tokenUtils.getUserInfo().getOpenId());
            }
        }else {
           String res1 =  TianCongUtils.addSample(tokenUtils.getUserInfo().getOpenId(), null, upload.getContent(), new File(path.replace("\\uploadFile", "") + upload.getPath()));
            com.alibaba.fastjson.JSONObject object = JSON.parseObject(res1);
            Double score =  object.getDouble("score");
            if(score>0.7)
            {
                return Result.<Upload>builder().data(res).success().build();
            }else{
                return Result.<Upload>builder().data(res).fail().message("声纹不匹配!").build();
            }
        }
        return Result.<Upload>builder().data(res).build();
    }

    @Override
    public Result<Upload> tts(String content)
    {
        if(content.contains("}"))
       {
        content = content.substring(content.indexOf("}"));
       }
        TtsResponse res = BaiDuUtils.getClient().synthesis(content, "zh", 1, null);
        byte[] data = res.getData();
        JSONObject res1 = res.getResult();
        System.out.println(res1);
        if (data != null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(new Date());
                String newName = UUID.randomUUID().toString() + ".mp3";
                File folder = new File(path + format);
                if (!folder.isDirectory()) {
                    folder.mkdirs();
                }
                File targetFile = new File(path + format+"/"+newName);
                if(!targetFile.exists()) {
                    targetFile.createNewFile();
                }
                Util.writeBytesToFileSystem(data, path + format+"/"+newName);
                Upload upload = new Upload();
                upload.setType("tts");
                upload.setContent(content);
                upload.setOriginName(newName);
                upload.setPath("/uploadFile/" + format +"/"+ newName);
                Upload  result = uploadRepository.saveAndFlush(upload);
                return Result.<Upload>builder().data(result).build();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


}
